package cn.hzu580.interceptor;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

import cn.hzu580.entity.User;
import cn.hzu580.service.UserService;
import cn.hzu580.vo.UserVO;

public class PermissionInterceptor extends MethodFilterInterceptor{


	@Resource(name="user")
	private UserService userService;
	
	@Override
	protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
		if(actionInvocation.getProxy().getMethod().equals("login")){
			String uid = ServletActionContext.getRequest().getParameter("uid");
			String tel = ServletActionContext.getRequest().getParameter("tel");
			UserVO vo = new UserVO();
			vo.setUid(uid);
			vo.setTel(tel);
			User user = userService.get(vo);
			String permission = user.getPermission();
			if(permission.charAt(0) == '1'){
				ServletActionContext.getResponse().getWriter().print("failed_no_permission");
				ServletActionContext.getResponse().setStatus(401);
				return Action.NONE;
			}
			
		}
		String uid = (String) ActionContext.getContext().getSession().get("uid");
		String tel = ServletActionContext.getRequest().getParameter("tel");
		UserVO vo = new UserVO();
		vo.setUid(uid);
		vo.setTel(tel);
		User user = userService.get(vo);
		String permission = user.getPermission();
		if(permission.charAt(1) == '1' && actionInvocation.getProxy().getMethod().equals("create")){
			ServletActionContext.getResponse().getWriter().print("failed_no_permission");
			ServletActionContext.getResponse().setStatus(401);
			return Action.NONE;
		}
		if(permission.charAt(2) == '1' && actionInvocation.getProxy().getMethod().equals("write")){
			ServletActionContext.getResponse().getWriter().print("failed_no_permission");
			ServletActionContext.getResponse().setStatus(401);
			return Action.NONE;
		}
		actionInvocation.invoke();
		return Action.NONE;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	
	
	
}
